<template>
  <div class="building-management">
    <!-- 小区信息 -->
    <div class="community-info">
      <el-form :model="communityForm" label-width="80px">
        <el-form-item label="小区名称">
          <el-select v-model="selectedCommunity" placeholder="请选择小区" @change="handleCommunityChange">
            <el-option 
              v-for="item in communitys" 
              :key="item.communityId" 
              :label="item.communityName" 
              :value="item.communityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小区地址">
          <span class="address-text">{{ communityAddress }}</span>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 类型标签 -->
    <div class="type-tabs">
      <el-tag
        v-for="(tab, index) in tabs"
        :key="tab.categoryId"
        :type="tab.active ? 'primary' : ''"
        :class="{ 'active-tab': tab.active }"
        @click="handleTabClick(tab)"
      >
        {{ tab.categoryName }}
      </el-tag>
    </div>

    <!-- 楼栋列表与建筑展示 -->
    <div class="building-container">
      <div class="building-list">
        <el-button type="primary" @click="showAddBuildingDialog" class="add-building-btn">
          + 增加楼栋
        </el-button>
        <el-tree
          :data="buildingTreeData"
          :props="treeProps"
          @node-click="handleBuildingClick"
          highlight-current
          :default-expand-all="true"
        ></el-tree>
      </div>
      
      <div class="building-display">
        <div class="building-header">
          <h3>{{ currentBuildingData.buildingName || '请选择楼栋' }}</h3>
          <div class="building-attrs" v-if="currentBuildingData.buildingName">
            <span>楼宇朝向：{{ currentBuildingData.buildingFace || '未知' }}</span>
            <span>楼高：{{ currentBuildingData.buildingHeight || '未知' }}米</span>
            <span>楼宇结构：{{ currentBuildingData.buildingStructure || '未知' }}</span>
            <span>单元数：{{ currentBuildingData.buildingUnit || '未知' }}</span>
            <span>楼层数：{{ currentBuildingData.buildingFloor || '未知' }}</span>
          </div>
          <div class="building-actions" v-if="currentBuildingData.buildingName">
            <el-button type="primary" @click="showAddHouseDialog">添加房屋</el-button>
            <el-button @click="showChargeStandardDialog">收费标准设置</el-button>
            <el-button type="danger" @click="handleDeleteBuilding">删除楼栋</el-button>
            <el-button @click="getSelectedRoomsInfo">获取选中房屋</el-button>
          </div>
        </div>
        
        <!-- 房屋网格展示 - 只要有单元和楼层就显示网格结构 -->
        <div class="house-grid-container" v-if="floors.length > 0 && units.length > 0">
          <div class="grid-header">
            <div class="empty-cell"></div>
            <div 
              v-for="unit in units" 
              :key="unit" 
              class="unit-header"
            >
              单元{{ unit }}
            </div>
          </div>
          
          <div
            v-for="floor in floors"
            :key="floor"
            class="floor-row"
          >
            <div class="floor-header">{{ floor }}楼</div>
            <div
              v-for="unit in units"
              :key="unit"
              class="unit-cell"
            >
              <!-- 显示该单元该楼层的房间，如果没有房间则显示空状态 -->
              <template v-if="getRoomsByFloorUnit(floor, unit).length > 0">
                <div
                  v-for="room in getRoomsByFloorUnit(floor, unit)"
                  :key="room.roomId"
                  class="room-item"
                  @click="handleRoomClick(room)"
                >
                  <div class="room-content">
                    <el-checkbox 
                      :value="isRoomSelected(room)" 
                      @change="handleRoomCheck(room, $event)"
                      @click.stop
                      class="room-checkbox"
                    ></el-checkbox>
                    <span class="room-number">{{ room.roomNumber }}</span>
                    <el-button
                      icon="el-icon-more"
                      type="text"
                      class="room-more-btn"
                      @click.stop="handleRoomMore(room, $event)"
                    ></el-button>
                  </div>
                </div>
              </template>
              <div v-else class="empty-room">
                <span class="empty-room-text">暂无房间</span>
                <el-button 
                  type="text" 
                  icon="el-icon-plus" 
                  class="add-room-btn"
                  @click="addRoomToPosition(floor, unit)"
                  title="在此位置添加房间"
                ></el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-building">
          <el-empty :description="currentBuildingData.buildingName ? '请先设置楼栋的单元数和楼层数' : '请选择楼栋查看房屋信息'" />
        </div>
      </div>
    </div>

    <!-- 新增楼栋对话框 -->
    <el-dialog
      title="楼栋设置"
      :visible.sync="addBuildingDialogVisible"
      width="50%"
      @close="handleAddBuildingDialogClose"
    >
      <el-form 
        :model="buildingForm" 
        ref="buildingFormRef" 
        :rules="buildingFormRules" 
        label-width="120px"
      >
        <el-form-item label="楼栋名称" prop="name">
          <el-input 
            v-model="buildingForm.name" 
            placeholder="例如：1栋"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="楼宇朝向" prop="orientation">
          <el-select v-model="buildingForm.orientation" placeholder="请选择朝向">
            <el-option label="南" value="南"></el-option>
            <el-option label="北" value="北"></el-option>
            <el-option label="东" value="东"></el-option>
            <el-option label="西" value="西"></el-option>
            <el-option label="东南" value="东南"></el-option>
            <el-option label="西南" value="西南"></el-option>
            <el-option label="东北" value="东北"></el-option>
            <el-option label="西北" value="西北"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼高" prop="height">
          <el-input 
            v-model="buildingForm.height" 
            placeholder="请输入楼高"
            type="number"
            min="1"
            max="1000"
            step="0.1"
          >
            <template slot="append">米</template>
          </el-input>
        </el-form-item>
        <el-form-item label="楼宇结构" prop="structure">
          <el-select v-model="buildingForm.structure" placeholder="请选择结构">
            <el-option label="框架结构" value="框架结构"></el-option>
            <el-option label="砖混结构" value="砖混结构"></el-option>
            <el-option label="钢结构" value="钢结构"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元数" prop="unitCount">
          <el-input-number 
            v-model="buildingForm.unitCount" 
            :min="1" 
            :max="10"
            placeholder="请输入单元数"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="楼层数" prop="floorCount">
          <el-input-number 
            v-model="buildingForm.floorCount" 
            :min="1" 
            :max="50"
            placeholder="请输入楼层数"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addBuildingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBuilding">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加房屋对话框 -->
     <el-dialog
      title="添加房屋"
      :visible.sync="addHouseDialogVisible"
      width="60%"
      @close="handleAddHouseDialogClose"
    >
      <el-form :model="houseForm" ref="houseFormRef" :rules="houseFormRules" label-width="100px">
        <el-form-item label="选择单元">
          <el-select 
            v-model="houseForm.selectedUnit" 
            placeholder="请选择单元"
            @change="onFloorOrUnitChange"
          >
            <el-option 
              v-for="unit in units" 
              :key="unit" 
              :label="`${unit}单元`" 
              :value="unit"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择楼层">
          <el-select 
            v-model="houseForm.selectedFloor" 
            placeholder="请选择楼层"
            @change="onFloorOrUnitChange"
          >
            <el-option 
              v-for="floor in floors" 
              :key="floor" 
              :label="`${floor}楼`" 
              :value="floor"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="房号范围" prop="roomNoRange">
          <el-input
            v-model="houseForm.roomNoRange"
            :placeholder="getRoomNoPlaceholder()"
            style="width: 200px;"
          ></el-input>
          <span class="tip-text">（{{ getRoomNoTip() }}）</span>
        </el-form-item>
        
        <el-form-item label="房屋信息">
          <div class="house-info-grid">
            <el-input
              v-model="houseForm.buildingArea"
              placeholder="建筑面积"
              style="width: 120px;"
            >
              <template slot="append">㎡</template>
            </el-input>
            <el-input
              v-model="houseForm.internalArea"
              placeholder="套内面积"
              style="width: 120px; margin-left: 10px;"
            >
              <template slot="append">㎡</template>
            </el-input>
            <el-input
              v-model="houseForm.publicArea"
              placeholder="公摊面积"
              style="width: 120px; margin-left: 10px;"
            >
              <template slot="append">㎡</template>
            </el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="房屋户型">
          <div class="house-type-grid">
            <el-input
              v-model="houseForm.roomCount"
              placeholder="室"
              style="width: 80px;"
              type="number"
              min="0"
            ></el-input>
            <span class="type-separator">室</span>
            <el-input
              v-model="houseForm.hallCount"
              placeholder="厅"
              style="width: 80px; margin-left: 10px;"
              type="number"
              min="0"
            ></el-input>
            <span class="type-separator">厅</span>
            <el-input
              v-model="houseForm.bathroomCount"
              placeholder="卫"
              style="width: 80px; margin-left: 10px;"
              type="number"
              min="0"
            ></el-input>
            <span class="type-separator">卫</span>
          </div>
          <div class="house-type-preview" v-if="houseForm.roomCount || houseForm.hallCount || houseForm.bathroomCount">
            户型预览：{{ getHouseTypePreview() }}
          </div>
        </el-form-item>
        
        <el-form-item label="朝向">
          <el-select v-model="houseForm.orientation" placeholder="请选择朝向">
            <el-option label="南" value="南"></el-option>
            <el-option label="北" value="北"></el-option>
            <el-option label="东" value="东"></el-option>
            <el-option label="西" value="西"></el-option>
            <el-option label="东南" value="东南"></el-option>
            <el-option label="西南" value="西南"></el-option>
            <el-option label="东北" value="东北"></el-option>
            <el-option label="西北" value="西北"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addHouseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addHouse">确定</el-button>
      </div>
    </el-dialog>

    <!-- 收费标准设置对话框 -->
    <el-dialog
      title="收费标准设置"
      :visible.sync="chargeStandardDialogVisible"
      width="500px"
      @close="handleChargeStandardDialogClose"
    >
      <div class="charge-standard-content">
        <div class="selected-rooms-info" v-if="selectedRooms.length > 0">
          <p>已选中 <span class="selected-count">{{ selectedRooms.length }}</span> 个房屋</p>
          <p class="tip-text">将为这些房屋绑定收费标准</p>
        </div>
        <div class="selected-rooms-info" v-else>
          <p class="warning-text">请先选择要绑定收费标准的房屋</p>
        </div>
        
        <el-form :model="chargeStandardForm" label-width="100px">
          <el-form-item label="收费标准">
            <el-select 
              v-model="chargeStandardForm.standard" 
              placeholder="请选择收费标准"
              style="width: 100%"
            >
              <el-option 
                v-for="item in pricingOptions" 
                :key="item.pricingId" 
                :label="item.pricingName" 
                :value="item.pricingId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        
        <div class="pricing-list" v-if="pricingOptions.length > 0">
          <h4>可选收费标准：</h4>
          <div class="pricing-item" v-for="item in pricingOptions" :key="item.pricingId">
            {{ item.pricingName }}
          </div>
        </div>
        <div v-else class="no-pricing">
          <p>该小区暂无收费标准</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chargeStandardDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="saveChargeStandard" 
          :disabled="selectedRooms.length === 0 || !chargeStandardForm.standard"
        >
          确定绑定
        </el-button>
      </div>
    </el-dialog>

    <!-- 房屋操作下拉菜单 -->
    <el-dropdown
      ref="roomDropdown"
      :visible.sync="roomDropdownVisible"
      trigger="manual"
    >
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click="handleRoomEdit">
          <i class="el-icon-edit"></i>编辑房屋
        </el-dropdown-item>
        <el-dropdown-item @click="handleRoomCharge">
          <i class="el-icon-money"></i>收费标准
        </el-dropdown-item>
        <el-dropdown-item @click="handleRoomDetail">
          <i class="el-icon-document"></i>房屋详情
        </el-dropdown-item>
        <el-dropdown-item @click="handleRoomDelete" divided>
          <i class="el-icon-delete" style="color: #f56c6c;"></i>删除房屋
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
export default {
  data() {
    // 房屋表单验证规则
    const validateRoomNoRange = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入房号范围'));
        return;
      }
      
      if (!/^\d+-\d+$/.test(value)) {
        callback(new Error('房号范围格式错误，请使用"101-109"格式'));
        return;
      }
      
      const [start, end] = value.split('-').map(Number);
      const selectedFloor = this.houseForm.selectedFloor;
      
      // 根据楼层确定房号范围
      let minRoom, maxRoom;
      if (selectedFloor < 10) {
        // 1-9楼：房号为3位数，如101-109
        minRoom = selectedFloor * 100 + 1;  // 如1楼：101，2楼：201
        maxRoom = selectedFloor * 100 + 99; // 如1楼：199，2楼：299
      } else {
        // 10楼及以上：房号为4位数，如1001-1009
        minRoom = selectedFloor * 100 + 1;   // 如10楼：1001，11楼：1101
        maxRoom = selectedFloor * 100 + 99;  // 如10楼：1099，11楼：1199
      }
      
      // 验证起始房号
      if (start < minRoom) {
        callback(new Error(`${selectedFloor}楼的房号起始范围应为${minRoom}`));
        return;
      }
      
      if (start > maxRoom) {
        callback(new Error(`${selectedFloor}楼的房号起始范围不能超过${maxRoom}`));
        return;
      }
      
      // 验证结束房号
      if (end < minRoom) {
        callback(new Error(`${selectedFloor}楼的房号结束范围应为${minRoom}`));
        return;
      }
      
      if (end > maxRoom) {
        callback(new Error(`${selectedFloor}楼的房号结束范围不能超过${maxRoom}`));
        return;
      }
      
      // 验证起始房号不能大于结束房号
      if (start > end) {
        callback(new Error('起始房号不能大于结束房号'));
        return;
      }
      
      // 验证房号格式是否正确（位数匹配）
      if (selectedFloor < 10 && (start < 100 || end > 999)) {
        callback(new Error(`1-9楼的房号应为3位数（101-199范围）`));
        return;
      }
      
      if (selectedFloor >= 10 && (start < 1000 || end > 9999)) {
        callback(new Error(`10楼及以上的房号应为4位数（1001-1999范围）`));
        return;
      }
      
      callback();
    };

    // 楼栋表单验证规则
    const validateBuildingName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入楼栋名称'));
      } else if (value.length > 50) {
        callback(new Error('楼栋名称不能超过50个字符'));
      } else {
        callback();
      }
    };

    const validateHeight = (rule, value, callback) => {
      if (value && (value < 1 || value > 1000)) {
        callback(new Error('楼高应在1-1000米之间'));
      } else {
        callback();
      }
    };

    return {
      communitys:[],//所有小区
      selectedCommunity: '',
      communityAddress: '',
      communityForm: {},
      commId:'',//用来装小区选择框改变时的id
      categoryId:'',//用来装楼栋类型选择框改变时的id
      tabs: [],
      activeTab: null ,// 记录当前激活的tab
      
      // 楼栋数据
      buildingTreeData: [],
      treeProps: {
        children: 'children',
        label: 'buildingName'
      },
      buildingId: '',//当前选中的楼栋ID
      
      // 当前楼栋的详细信息
      currentBuildingData: {},
      
      // 房屋数据
      units: [],
      floors: [],
      rooms: [],
      
      // 选中的房屋数组
      selectedRooms: [],
      
      // 收费标准选项
      pricingOptions: [],
      
      // 对话框控制
      addBuildingDialogVisible: false,
      addHouseDialogVisible: false,
      chargeStandardDialogVisible: false,
      roomDropdownVisible: false,
      
      // 表单数据
      buildingForm: {
        name: '',
        orientation: '',
        height: '',
        structure: '',
        unitCount: 1,
        floorCount: 1
      },
      houseForm: {
        selectedUnit: 1,
        selectedFloor: 1,
        roomNoRange: '',
        orientation: '',
        buildingArea: '',
        internalArea: '',
        publicArea: '',
        roomCount: '',
        hallCount: '',
        bathroomCount: ''
      },
      chargeStandardForm: {
        standard: ''
      },
      
      currentRoom: null,

      // 房屋表单验证规则
      houseFormRules: {
        roomNoRange: [
          { required: true, validator: validateRoomNoRange, trigger: 'blur' }
        ]
      },
      
      // 楼栋表单验证规则
      buildingFormRules: {
        name: [
          { required: true, validator: validateBuildingName, trigger: 'blur' }
        ],
        height: [
          { validator: validateHeight, trigger: 'blur' }
        ],
        unitCount: [
          { required: true, message: '请输入单元数', trigger: 'blur' }
        ],
        floorCount: [
          { required: true, message: '请输入楼层数', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.initPage();
  },
  methods: {
    // 检查房间是否被选中
    isRoomSelected(room) {
      return this.selectedRooms.some(selectedRoom => selectedRoom.roomId === room.roomId);
    },
    
    // 处理房间选择/取消选择
    handleRoomCheck(room, checked) {
      console.log('房间选择/取消选择:', room, checked);
      if (checked) {
        // 添加房间到选中数组
        if (!this.isRoomSelected(room)) {
          this.selectedRooms.push(room);
        }
      } else {
        // 从选中数组中移除房间
        const index = this.selectedRooms.findIndex(selectedRoom => selectedRoom.roomId === room.roomId);
        if (index !== -1) {
          this.selectedRooms.splice(index, 1);
        }
      }
    },
    
    // 获取选中房屋的完整信息
    getSelectedRoomsInfo() {
      if (this.selectedRooms.length === 0) {
        this.$message.warning('请先选择房屋');
        return;
      }
      
      // 格式化选中房屋信息
      const selectedRoomsInfo = this.selectedRooms.map(room => ({
        roomId: room.roomId,
        unitId: room.unitId,
        floor: room.floor,
        roomNumber: room.roomNumber,
        fullRoomNumber: `${this.getBuildingNumber()}-${room.unitId}-${room.roomNumber}`
      }));
      
      console.log('选中的房屋信息:', selectedRoomsInfo);
      this.$message.success(`已选中 ${selectedRoomsInfo.length} 个房屋，详细信息已输出到控制台`);
      
      // 在实际应用中，这里可以调用API处理选中房屋
      // 例如：this.processSelectedRooms(selectedRoomsInfo);
      
      return selectedRoomsInfo;
    },
    
    // 获取房号输入框的提示文本
    getRoomNoPlaceholder() {
      const floor = this.houseForm.selectedFloor;
      if (floor < 10) {
        return `${floor}01-${floor}09`;
      } else {
        return `${floor}001-${floor}009`;
      }
    },
    
    // 获取房号提示信息
    getRoomNoTip() {
      const floor = this.houseForm.selectedFloor;
      if (floor < 10) {
        return `请输入${floor}楼的3位数房号，如${floor}01-${floor}09`;
      } else {
        return `请输入${floor}楼的4位数房号，如${floor}001-${floor}009`;
      }
    },
    
    // 当楼层或单元改变时，清空并重新验证房号范围
    onFloorOrUnitChange() {
      this.houseForm.roomNoRange = '';
      if (this.$refs.houseFormRef) {
        this.$refs.houseFormRef.clearValidate('roomNoRange');
      }
    },

    // 初始化页面
    async initPage() {
      await this.getCommunitys();
      await this.getBuildingTypes();
      if (this.commId && this.categoryId) {
        await this.getBuildingsByCommunityIdAndType(this.categoryId, this.commId);
        // 默认选择第一个楼栋
        if (this.buildingTreeData.length > 0) {
          this.handleBuildingClick(this.buildingTreeData[0]);
        }
      }
    },

    //获取所有小区
    async getCommunitys() {
      try {
        const resp = await this.$axios.get('http://192.168.214.129:8080/community/selcomm');
        if(resp.data.code === 200){
          this.communitys = resp.data.data;
          if(this.communitys && this.communitys.length > 0) {
            this.commId = this.communitys[0].communityId;
            this.selectedCommunity = this.communitys[0].communityId;
            this.communityAddress = this.communitys[0].communityAddress || '未知地址';
          }
        }
      } catch (error) {
        console.error('获取小区失败:', error);
      }
    },

    //小区选择时改变地址
    async handleCommunityChange(communityId) {
      this.commId = communityId;
      const selected = this.communitys.find(item => item.communityId === communityId);
      if(selected) {
        this.communityAddress = selected.communityAddress || '未知地址';
      }
      await this.getBuildingsByCommunityIdAndType(this.categoryId, this.commId);
      // 重新选择第一个楼栋
      if (this.buildingTreeData.length > 0) {
        this.handleBuildingClick(this.buildingTreeData[0]);
      } else {
        // 如果没有楼栋数据，清空当前显示
        this.currentBuildingData = {};
        this.units = [];
        this.floors = [];
        this.rooms = [];
        this.selectedRooms = []; // 清空选中的房屋
      }
    },

    //查询所有楼栋类型
    async getBuildingTypes() {
      try {
        const resp = await this.$axios.get('http://192.168.214.129:8080/buildingCategory/all');
        if(resp.data.code === 200) {
          this.tabs = resp.data.data.map(item => ({
            ...item,
            active: false
          }));
          // 默认激活第一个tab
          if(this.tabs.length > 0) {
            this.tabs[0].active = true;
            this.categoryId = this.tabs[0].categoryId;
          }
        }
      } catch (error) {
        console.error('获取楼栋类型失败:', error);
      }
    },

    //选择楼栋类型时改变的方法
    async handleTabClick(tab) {
      this.tabs.forEach(t => t.active = false);
      tab.active = true;
      this.categoryId = tab.categoryId;
      await this.getBuildingsByCommunityIdAndType(this.categoryId, this.commId);
      // 重新选择第一个楼栋
      if (this.buildingTreeData.length > 0) {
        this.handleBuildingClick(this.buildingTreeData[0]);
      } else {
        this.currentBuildingData = {};
        this.units = [];
        this.floors = [];
        this.rooms = [];
        this.selectedRooms = []; // 清空选中的房屋
      }
    },
    
    //根据小区id和楼栋类型id获取所有楼栋
    async getBuildingsByCommunityIdAndType(buildingType, communityId) {
      try {
        const resp = await this.$axios.get('http://192.168.214.129:8080/building/bycategoryId', {
          params: {
            categoryId: buildingType,
            commId: communityId
          }
        });
        if(resp.data.code === 200) {
          this.buildingTreeData = resp.data.data || [];
        }
      } catch (error) {
        console.error('获取楼栋列表失败:', error);
        this.buildingTreeData = [];
      }
    },

    // 点击楼栋获取详细信息
    async handleBuildingClick(data) {
      this.buildingId = data.buildingId;
      this.selectedRooms = []; // 切换楼栋时清空选中的房屋
      await this.getBuildingDetail(this.buildingId);
    },
    
    // 获取楼栋详细信息
    async getBuildingDetail(buildingId) {
      try {
        const resp = await this.$axios.get('http://192.168.214.129:8080/building/roombyid', {
          params: { buildingId: buildingId }
        });
        
        if (resp.data.code === 200) {
          console.log('楼栋详情:', resp);
          const buildingData = resp.data.data;
          this.currentBuildingData = buildingData;
          
          // 处理单元数据 - 始终根据楼栋的单元数生成
          this.units = Array.from({ length: buildingData.buildingUnit || 1 }, (_, i) => i + 1);
          
          // 处理楼层数据 - 始终根据楼栋的楼层数生成（从高到低显示）
          this.floors = Array.from({ length: buildingData.buildingFloor || 1 }, (_, i) => buildingData.buildingFloor - i);
          
          // 处理房间数据 - 即使没有房间也要渲染网格结构
          this.rooms = (buildingData.roomByBuildIdDtos || []).map(room => ({
            roomId: room.roomId,
            unitId: room.unitId,
            floor: Math.floor(room.roomNumber / 100),
            roomNumber: room.roomNumber,
            checked: false
          }));
        }
      } catch (error) {
        console.error('获取楼栋详情失败:', error);
        this.$message.error('获取楼栋信息失败');
      }
    },

    // 获取小区的收费标准
    async getPricingByCommunityId() {
      if (!this.commId) {
        this.pricingOptions = [];
        return;
      }
      
      try {
        const resp = await this.$axios.get('http://192.168.214.129:8080/pricing/getpricebycommId', {
          params: { commId: this.commId }
        });
        
        if (resp.data.code === 200) {
          this.pricingOptions = resp.data.data || [];
        } else {
          this.pricingOptions = [];
          this.$message.warning('获取收费标准失败');
        }
      } catch (error) {
        console.error('获取收费标准失败:', error);
        this.pricingOptions = [];
        this.$message.error('获取收费标准失败');
      }
    },

    // 在指定位置添加房间
    addRoomToPosition(floor, unit) {
      this.houseForm.selectedUnit = unit;
      this.houseForm.selectedFloor = floor;
      this.houseForm.roomNoRange = '101-101'; // 默认添加一个房间
      this.addHouseDialogVisible = true;
    },

    // 处理添加房屋对话框关闭
    handleAddHouseDialogClose() {
      this.houseForm = {
        selectedUnit: this.units[0] || 1,
        selectedFloor: this.floors[0] || 1,
        roomNoRange: '',
        orientation: '',
        buildingArea: '',
        internalArea: '',
        publicArea: '',
        roomCount: '',
        hallCount: '',
        bathroomCount: ''
      };
      if (this.$refs.houseFormRef) {
        this.$refs.houseFormRef.clearValidate();
      }
    },

    // 处理添加楼栋对话框关闭
    handleAddBuildingDialogClose() {
      this.buildingForm = {
        name: '',
        orientation: '',
        height: '',
        structure: '',
        unitCount: 1,
        floorCount: 1
      };
      // 使用 $refs 来访问表单引用
      if (this.$refs.buildingFormRef) {
        this.$refs.buildingFormRef.clearValidate();
      }
    },

    // 处理收费标准对话框关闭
    handleChargeStandardDialogClose() {
      this.chargeStandardForm.standard = '';
    },

    // 获取户型预览
    getHouseTypePreview() {
      const { roomCount, hallCount, bathroomCount } = this.houseForm;
      const parts = [];
      if (roomCount) parts.push(`${roomCount}室`);
      if (hallCount) parts.push(`${hallCount}厅`);
      if (bathroomCount) parts.push(`${bathroomCount}卫`);
      return parts.join('-') || '暂无户型信息';
    },

    showAddBuildingDialog() {
      // 检查是否已选择小区和楼栋类型
      if (!this.commId) {
        this.$message.warning('请先选择小区');
        return;
      }
      
      if (!this.categoryId) {
        this.$message.warning('请先选择楼栋类型');
        return;
      }
      
      this.addBuildingDialogVisible = true;
      this.buildingForm = {
        name: '',
        orientation: '',
        height: '',
        structure: '',
        unitCount: 1,
        floorCount: 1
      };
      
      // 使用 $nextTick 确保 DOM 已经更新
      this.$nextTick(() => {
        if (this.$refs.buildingFormRef) {
          this.$refs.buildingFormRef.clearValidate();
        }
      });
    },
    
    // 添加楼栋
    async addBuilding() {
      try {
        // 检查表单引用是否存在
        if (!this.$refs.buildingFormRef) {
          this.$message.error('表单初始化失败，请重试');
          return;
        }
        
        // 验证表单
        const valid = await this.$refs.buildingFormRef.validate();
        if (!valid) {
          this.$message.warning('请完善表单信息');
          return;
        }

        // 准备提交数据
        const submitData = {
          buildingId: '', // 新增时传空，后端生成
          communityId: this.commId,
          categoryId: this.categoryId,
          buildingName: this.buildingForm.name,
          buildingFace: this.buildingForm.orientation,
          buildingHeight: this.buildingForm.height ? parseFloat(this.buildingForm.height) : null,
          buildingStructure: this.buildingForm.structure,
          buildingUnit: this.buildingForm.unitCount,
          buildingFloor: this.buildingForm.floorCount
        };

        console.log('提交的楼栋数据:', submitData);

        // 调用API添加楼栋
        const response = await this.$axios.post('http://192.168.214.129:8080/building/addbuild', submitData);
        
        if (response.data.code === 200) {
          this.$message.success('楼栋添加成功');
          this.addBuildingDialogVisible = false;
          
          // 刷新楼栋列表
          await this.getBuildingsByCommunityIdAndType(this.categoryId, this.commId);
          
          // 如果添加成功，自动选择新添加的楼栋
          if (this.buildingTreeData.length > 0) {
            const newBuilding = this.buildingTreeData.find(building => 
              building.buildingName === this.buildingForm.name
            );
            if (newBuilding) {
              await this.handleBuildingClick(newBuilding);
            }
          }
        } else {
          this.$message.error(response.data.message || '楼栋添加失败');
        }

      } catch (error) {
        console.error('添加楼栋失败:', error);
        if (error.response && error.response.data) {
          this.$message.error(error.response.data.message || '添加楼栋失败');
        } else {
          this.$message.error('添加楼栋失败，请重试');
        }
      }
    },
    
    showAddHouseDialog() {
      if (!this.currentBuildingData.buildingName) {
        this.$message.warning('请先选择楼栋');
        return;
      }
      this.addHouseDialogVisible = true;
      this.houseForm = {
        selectedUnit: this.units[0] || 1,
        selectedFloor: this.floors[0] || 1,
        roomNoRange: '',
        orientation: '',
        buildingArea: '',
        internalArea: '',
        publicArea: '',
        roomCount: '',
        hallCount: '',
        bathroomCount: ''
      };
    },
    
    // 添加房屋
    async addHouse() {
      try {
        // 验证表单
        const valid = await this.$refs.houseFormRef.validate();
        if (!valid) return;

        // 解析房号范围
        const [startRoom, endRoom] = this.houseForm.roomNoRange.split('-').map(Number);
        
        // 生成房号数组
        const roomNumbers = [];
        for (let i = startRoom; i <= endRoom; i++) {
          roomNumbers.push(i);
        }

        // 准备提交数据
        const submitData = {
          roomId:'',
          buildingId: this.buildingId, // 楼栋ID
          unitId: this.houseForm.selectedUnit, // 单元号
          roomNumbers: roomNumbers, // 房号数组
          roomArea: this.houseForm.buildingArea ? parseFloat(this.houseForm.buildingArea) : null, // 建筑面积
          roomInArea: this.houseForm.internalArea ? parseFloat(this.houseForm.internalArea) : null, // 室内面积
          commonArea: this.houseForm.publicArea ? parseFloat(this.houseForm.publicArea) : null, // 公摊面积
          orientation: this.houseForm.orientation, // 朝向
          roomType: this.formatHouseType(), // 户型（格式：4-5-6）
          roomStatus:0,
          roomMoney:0,
          pricingId:'',
          // 生成完整的房间号（如：4-2-101）
          fullRoomNumbers: roomNumbers.map(roomNo => 
            `${this.getBuildingNumber()}-${this.houseForm.selectedUnit}-${roomNo}`
          )
        };

        console.log('提交的房屋数据:', submitData);

        // 调用API添加房屋
        const response = await this.$axios.post('http://192.168.214.129:8080/room/addRoom', submitData);
        
        if (response.data.code === 200) {
          this.$message.success('房屋添加成功');
          this.addHouseDialogVisible = false;
          // 刷新楼栋详情
          await this.getBuildingDetail(this.buildingId);
        } else {
          this.$message.error(response.data.message || '房屋添加失败');
        }

      } catch (error) {
        console.error('添加房屋失败:', error);
        if (error.response && error.response.data) {
          this.$message.error(error.response.data.message || '添加房屋失败');
        } else {
          this.$message.error('添加房屋失败，请重试');
        }
      }
    },

    // 格式化户型数据
    formatHouseType() {
      const { roomCount, hallCount, bathroomCount } = this.houseForm;
      return `${roomCount || 0}-${hallCount || 0}-${bathroomCount || 0}`;
    },

    // 获取楼栋编号（从楼栋名称中提取数字）
    getBuildingNumber() {
      if (!this.currentBuildingData.buildingName) return '';
      // 从楼栋名称中提取数字，如"1号楼" -> "1"
      const match = this.currentBuildingData.buildingName.match(/(\d+)/);
      return match ? match[1] : '';
    },

    // 根据楼层和单元获取房间（修改房间号显示格式）
    getRoomsByFloorUnit(floor, unit) {
      return this.rooms.filter(room => 
        room.unitId === unit && room.floor === floor
      ).map(room => ({
        ...room,
        // 格式化显示的房间号（如：4-2-101）
        displayRoomNumber: `${this.getBuildingNumber()}-${room.unitId}-${room.roomNumber}`
      }));
    },
    
    // 显示收费标准设置对话框
    async showChargeStandardDialog() {
      if (!this.currentBuildingData.buildingName) {
        this.$message.warning('请先选择楼栋');
        return;
      }
      
      if (this.selectedRooms.length === 0) {
        this.$message.warning('请先选择要绑定收费标准的房屋');
        return;
      }
      
      // 获取小区的收费标准
      await this.getPricingByCommunityId();
      
      this.chargeStandardDialogVisible = true;
      this.chargeStandardForm.standard = '';
    },
    
    // 保存收费标准（绑定房屋与收费标准）
    async saveChargeStandard() {
      if (!this.chargeStandardForm.standard) {
        this.$message.error('请选择收费标准');
        return;
      }
      
      if (this.selectedRooms.length === 0) {
        this.$message.error('请先选择房屋');
        return;
      }
      
      try {
        // 准备提交数据
        console.log(this.selectedRooms);
        const submitData = {
          roomId: this.selectedRooms.map(room => room.roomId),
          pricingId: this.chargeStandardForm.standard
        };

        console.log('绑定收费标准数据:', submitData);

        // 调用API绑定收费标准
        const response = await this.$axios.post('http://192.168.214.129:8080/room/bangroom', submitData);
        
        if (response.data.code === 200) {
          this.$message.success('收费标准绑定成功');
          this.chargeStandardDialogVisible = false;
          
          // 刷新楼栋详情以更新房屋信息
          await this.getBuildingDetail(this.buildingId);
          
          // 清空选中的房屋
          this.selectedRooms = [];
        } else {
          this.$message.error(response.data.message || '收费标准绑定失败');
        }

      } catch (error) {
        console.error('绑定收费标准失败:', error);
        if (error.response && error.response.data) {
          this.$message.error(error.response.data.message || '绑定收费标准失败');
        } else {
          this.$message.error('绑定收费标准失败，请重试');
        }
      }
    },
    
    // 修改房间点击事件，显示完整房间号
    handleRoomClick(room) {
      console.log('点击房间:', {
        ...room,
        fullRoomNumber: `${this.getBuildingNumber()}-${room.unitId}-${room.roomNumber}`
      });
    },
    
    handleRoomMore(room, event) {
      this.currentRoom = room;
      this.roomDropdownVisible = true;
      event.stopPropagation();
    },
    
    handleRoomEdit() {
      this.roomDropdownVisible = false;
      this.$message.info('编辑房屋功能开发中');
    },
    
    handleRoomCharge() {
      this.roomDropdownVisible = false;
      this.$message.info('收费标准功能开发中');
    },
    
    handleRoomDetail() {
      this.roomDropdownVisible = false;
      this.$message.info('房屋详情功能开发中');
    },
    
    handleRoomDelete() {
      this.$confirm('确定要删除这个房屋吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.roomDropdownVisible = false;
        this.$message.success('房屋删除成功');
        // 刷新楼栋详情
        this.getBuildingDetail(this.buildingId);
      }).catch(() => {
        this.roomDropdownVisible = false;
      });
    },
    
    handleDeleteBuilding() {
      this.$confirm('确定要删除这个楼栋吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除楼栋的逻辑
        console.log(this.buildingId);
        this.$axios.delete(`http://192.168.214.129:8080/building/delbuildbyid/${this.buildingId}`)
          .then(resp=>{
            if(resp.data.code === 200){
              this.$message.success('楼栋删除成功');
              // 刷新楼栋列表
              this.getBuildingsByCommunityIdAndType(this.categoryId, this.commId);
              // 清空当前显示
              this.currentBuildingData = {};
              this.units = [];
              this.floors = [];
              this.rooms = [];
              this.selectedRooms = []; // 清空选中的房屋
            }
            
          })
        
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.house-type-preview {
  margin-top: 8px;
  padding: 6px 12px;
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  color: #1890ff;
  font-size: 13px;
  font-weight: 500;
}

/* 收费标准对话框样式 */
.charge-standard-content {
  max-height: 400px;
  overflow-y: auto;
}

.selected-rooms-info {
  background: #f0f9ff;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
}

.selected-count {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
}

.tip-text {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.warning-text {
  color: #e6a23c;
  font-weight: bold;
}

.pricing-list {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pricing-list h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.pricing-item {
  padding: 5px 10px;
  background: white;
  margin-bottom: 5px;
  border-radius: 3px;
  border: 1px solid #ebeef5;
}

.no-pricing {
  text-align: center;
  padding: 20px;
  color: #909399;
}

/* 新增空房间样式 */
.empty-room {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  background: #f8f9fa;
  border: 1px dashed #dcdfe6;
  border-radius: 3px;
  color: #909399;
  font-size: 12px;
  position: relative;
}

.empty-room-text {
  margin-right: 5px;
}

.add-room-btn {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  padding: 2px;
  font-size: 12px;
}

.add-room-btn:hover {
  color: #409eff;
}

/* 其他样式保持不变 */
.building-attrs {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.building-attrs span {
  font-size: 14px;
  color: #606266;
  background: #f5f7fa;
  padding: 6px 12px;
  border-radius: 4px;
  white-space: nowrap;
}

.building-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.community-info {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.community-info .el-form {
  display: flex;
  align-items: center;
  gap: 40px;
}

.community-info .el-form-item {
  margin-bottom: 0;
}

.address-text {
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.type-tabs {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 15px;
}

.type-tabs .el-tag {
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
  text-align: center;
}

.type-tabs .el-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.type-tabs .active-tab {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.building-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 220px);
}

.building-list {
  width: 280px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.add-building-btn {
  margin-bottom: 20px;
  width: 100%;
  height: 40px;
  border-radius: 6px;
}

.building-list .el-tree {
  flex: 1;
  overflow-y: auto;
}

.building-display {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.building-header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.building-header h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}

.building-actions {
  display: flex;
  gap: 10px;
}

.house-grid-container {
  flex: 1;
  overflow: auto;
}

.grid-header {
  display: flex;
  margin-bottom: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
}

.empty-cell {
  width: 80px;
}

.unit-header {
  flex: 1;
  text-align: center;
  font-weight: bold;
  color: #409eff;
  padding: 5px;
}

.floor-row {
  display: flex;
  margin-bottom: 8px;
  align-items: stretch;
}

.floor-header {
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 4px;
  margin-right: 8px;
  font-weight: bold;
  color: #606266;
}

.unit-cell {
  flex: 1;
  margin: 0 4px;
  min-height: 60px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  background: #fafafa;
}

.room-item {
  margin-bottom: 4px;
}

.room-item:last-child {
  margin-bottom: 0;
}

.room-content {
  display: flex;
  align-items: center;
  background: white;
  padding: 6px 8px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  transition: all 0.3s ease;
}

.room-content:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.room-checkbox {
  margin-right: 8px;
}

.room-number {
  flex: 1;
  font-size: 12px;
  font-weight: bold;
  color: #303133;
}

.room-more-btn {
  padding: 2px;
  margin-left: 4px;
}

.empty-building {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.house-info-grid {
  display: flex;
  align-items: center;
}

.house-type-grid {
  display: flex;
  align-items: center;
}

.type-separator {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.tip-text {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

@media (max-width: 1200px) {
  .building-container {
    flex-direction: column;
    height: auto;
  }
  
  .building-list {
    width: 100%;
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .building-management {
    padding: 10px;
  }
  
  .community-info .el-form {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .building-actions {
    flex-wrap: wrap;
  }
}
</style>